package com.gexiaobao.pigeon.ui.fragment.mine.organization.activity

import android.annotation.SuppressLint
import android.os.Bundle
import android.view.LayoutInflater
import android.view.View
import android.view.inputmethod.EditorInfo
import androidx.appcompat.widget.AppCompatImageView
import androidx.appcompat.widget.AppCompatTextView
import androidx.core.view.isVisible
import androidx.core.widget.addTextChangedListener
import androidx.recyclerview.widget.LinearLayoutManager
import com.gexiaobao.pigeon.R
import com.gexiaobao.pigeon.app.base.BaseActivity
import com.gexiaobao.pigeon.app.eventViewModel
import com.gexiaobao.pigeon.app.ext.hideSoftKeyboard
import com.gexiaobao.pigeon.app.ext.init
import com.gexiaobao.pigeon.app.model.bean.BaseSignListResponse
import com.gexiaobao.pigeon.app.model.bean.CheckInfoListBean
import com.gexiaobao.pigeon.app.model.param.SInfoList
import com.gexiaobao.pigeon.app.model.param.SaveInfoSignParam
import com.gexiaobao.pigeon.app.util.RxToast
import com.gexiaobao.pigeon.app.util.StatusBarUtil
import com.gexiaobao.pigeon.databinding.ActivitySignPassGroupBinding
import com.gexiaobao.pigeon.ui.adapter.AdapterCheckSignInfo
import com.gexiaobao.pigeon.ui.adapter.AdapterPassSign
import com.gexiaobao.pigeon.ui.dialog.RxSignPassGroupNameDialog
import com.gexiaobao.pigeon.viewmodel.OrgRaceViewModel
import com.google.android.material.bottomsheet.BottomSheetDialog
import com.yanzhenjie.recyclerview.SwipeRecyclerView
import me.hgj.jetpackmvvm.ext.util.setOnclickNoRepeat
import me.hgj.jetpackmvvm.util.startActivity

/**
 * @Author      : hxw
 * @Date        : 2024/7/16 9:58
 * @Describe    : 关塞报名（立即报名）
 */
class ActivitySignPassGroup : BaseActivity<OrgRaceViewModel, ActivitySignPassGroupBinding>() {

    private lateinit var dialogBottom: BottomSheetDialog
    private var mBaseId = 0
    private var mMemberId = 0
    private var mOrderId = 0
    private var mVersion = 0
    private var ringId = ""
    private var featherColor = ""
    private var mTitle = ""
    private var isChecked = false
    private var isDisAble = false
    private val mAdapter: AdapterPassSign by lazy { AdapterPassSign(arrayListOf()) }
    private var pigeonRawList: MutableList<BaseSignListResponse.SignPigeonListBean> = arrayListOf()
    private val sInfoBean: ArrayList<SInfoList> = arrayListOf()

    private val mAdapterSure: AdapterCheckSignInfo by lazy { AdapterCheckSignInfo() }

    @SuppressLint("SetTextI18n")
    override fun initView(savedInstanceState: Bundle?) {
        StatusBarUtil.setTranslucentForImageView(this, 0, null)
        mDatabind.includeSearch.editQuery.hint = getString(R.string.search_by_ring)
        mTitle = intent.getStringExtra("teamName").toString()
        mDatabind.includeBar.tvTitle.text = mTitle
        mBaseId = intent.getIntExtra("baseId", 0)
        mMemberId = intent.getIntExtra("memberId", 0)
        mOrderId = intent.getIntExtra("orderId", 0)

        onRefresh()

        mDatabind.swipeRecyclerView.init(LinearLayoutManager(this), mAdapter)

        mAdapter.addChildClickViewIds(R.id.llSignGroup)
        mAdapter.setOnItemChildClickListener { _, view, position ->
            when (view.id) {
                R.id.llSignGroup -> showGroupNameDialogList(position, mAdapter.data[position].signStatus)
            }
        }

        mDatabind.swipeRefreshLayout.init {
            onRefresh()
        }

        mAdapter.setOnMultipleChoiceClickListener(object : AdapterPassSign.OnItemCheckClickListener {
            override fun onItemClick(isCheckedItem: Boolean, position: Int, list: List<BaseSignListResponse.SignPigeonListBean>) {
                ringId = mAdapter.data[position].ringId
                featherColor = mAdapter.data[position].featherColor
                isChecked = mAdapter.data[position].isChecked
                isDisAble = mAdapter.data[position].isDisAble

                if (!isCheckedItem) {
                    showGroupNameDialogList(position, mAdapter.data[position].signStatus)
                    return
                }
            }
        })

        mDatabind.includeSearch.editQuery.addTextChangedListener {
            mDatabind.includeSearch.ivClose.isVisible = it.toString().isNotEmpty()
        }

        mDatabind.includeSearch.editQuery.setOnEditorActionListener { _, i, _ ->
            when (i) {
                EditorInfo.IME_ACTION_SEARCH -> {
                    hideSoftKeyboard(this)
                    searchRingPigeon()
                }

                else -> {}
            }
            false
        }
    }

    private fun onRefresh() {
        showLoading(getString(R.string.loading))
        mViewModel.getAppBaseSignList(mBaseId.toString(), mMemberId, mOrderId)
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun showGroupNameDialogList(position: Int, signStatus: MutableList<BaseSignListResponse.SignPigeonListBean.SignStatusBean>) {
        val dialog = RxSignPassGroupNameDialog(this, signStatus)
        dialog.setTitle(mAdapter.data[position].ringId)
        dialog.setOnSureClickListener(object : RxSignPassGroupNameDialog.OnSureClickListener {
            override fun onItemClick(list: MutableList<BaseSignListResponse.SignPigeonListBean.SignStatusBean>) {
                if (list.isNotEmpty()) {
                    val isCheck: ArrayList<Boolean> = arrayListOf()
                    list.forEach {
                        isCheck.add(it.isCheck)
                    }
                    if (isCheck.contains(true)) {
                        mAdapter.data[position].isChecked = true
                        mAdapter.notifyItemChanged(position)
                    } else {
                        mAdapter.data[position].isChecked = false
                        mAdapter.notifyItemChanged(position)
                    }
                }
                mAdapter.notifyItemChanged(position)
                dialog.dismiss()
            }
        })
        dialog.setOnCancelClickListener(object : RxSignPassGroupNameDialog.OnCancelClickListener {
            override fun onItemClick(list: MutableList<BaseSignListResponse.SignPigeonListBean.SignStatusBean>) {
                mAdapter.data[position].signStatus.forEach {
                    if (it.isCheck) {
                        it.isCheck = false
                    }
                }
                mAdapter.data[position].isChecked = false
                mAdapter.notifyItemChanged(position)
                dialog.dismiss()
            }
        })
        dialog.setCanceledOnTouchOutside(false)
        dialog.setFullScreenWidth()
        dialog.show()
    }

    @SuppressLint("SetTextI18n", "NotifyDataSetChanged")
    override fun createObserver() {
        super.createObserver()
        /** app保存报名  */
        mViewModel.saveSignInfoResult.observe(this) {
            if (::dialogBottom.isInitialized) {
                dialogBottom.dismiss()
            }
            startActivity<ActivitySignPassOrderDetail>("orderId" to mOrderId, "teamName" to mTitle)
            eventViewModel.toRefreshData.value = true
            finish()
        }
        /** 获取报名表格列表  */
        mViewModel.signListResult.observe(this) {
            if (mDatabind.swipeRefreshLayout.isRefreshing) mDatabind.swipeRefreshLayout.isRefreshing = false
            val saveCnt = if (it.list.isNullOrEmpty()) {
                0
            } else {
                it.list.size
            }
            mDatabind.tvSignPassSaveCountPigeon.text = getString(R.string.Number_of_shed_feathers_str) + ":  $saveCnt" + getString(R.string.yu)
            mDatabind.tvSignPassEndTime.text = getString(R.string.Application_deadline_time) + ":  ${it.signDateRange}"
            mVersion = it.version
            if (it.list != null) {
                mAdapter.setList(it.list)
                mAdapter.notifyDataSetChanged()
                pigeonRawList.clear()
                pigeonRawList.addAll(it.list)

                it.list.forEachIndexed { index, signPigeonListBean ->
                    if (signPigeonListBean.signStatus.isNotEmpty()) {
                        for (signStatus in signPigeonListBean.signStatus) {
                            if (signStatus.isCheck) {
                                mAdapter.data[index].isChecked = true
                            }
                        }
                    }
                }
            }
        }
    }

    @SuppressLint("NotifyDataSetChanged")
    override fun onBindViewClick() {
        super.onBindViewClick()
        setOnclickNoRepeat(
            mDatabind.includeBar.ivBack,
            mDatabind.tvSubmitSignOrder,
            mDatabind.includeSearch.tvSearch,
            mDatabind.includeSearch.ivClose
        ) {
            when (it) {
                mDatabind.includeSearch.ivClose -> {
                    mDatabind.includeSearch.editQuery.setText("")
                    mAdapter.setList(pigeonRawList)
                    mAdapter.notifyDataSetChanged()
                }

                mDatabind.includeSearch.tvSearch -> searchRingPigeon()
                mDatabind.tvSubmitSignOrder -> submitOrderSign()
                mDatabind.includeBar.ivBack -> finish()
            }
        }
    }

    @SuppressLint("MissingInflatedId", "NotifyDataSetChanged", "SetTextI18n")
    private fun showBottomSureInfoDialog(checkInfoList: ArrayList<CheckInfoListBean>, sInfoBean: ArrayList<SInfoList>) {
        dialogBottom = BottomSheetDialog(this, R.style.BottomSheetDialog)
        val dialogView: View = LayoutInflater.from(this).inflate(R.layout.bottom_sure_info_dialog, null)
        val swipeRecyclerView = dialogView.findViewById<SwipeRecyclerView>(R.id.swipeRecyclerView)
        val tvCancel = dialogView.findViewById<AppCompatTextView>(R.id.tvCancel)
        val tvSUre = dialogView.findViewById<AppCompatTextView>(R.id.tvSure)
        val tvCountSignMoney = dialogView.findViewById<AppCompatTextView>(R.id.tvCountSignMoney)
        val tvSignPigeonTotal = dialogView.findViewById<AppCompatTextView>(R.id.tvSignPigeonTotal)
        val tvSignGroupTotal = dialogView.findViewById<AppCompatTextView>(R.id.tvSignGroupTotal)
        val ivCloseSingGroup = dialogView.findViewById<AppCompatImageView>(R.id.ivCloseSingGroup)
        tvSignPigeonTotal.text = checkInfoList.size.toString() + "羽,"
        swipeRecyclerView.init(LinearLayoutManager(this), mAdapterSure)
        mAdapterSure.setList(checkInfoList)
        mAdapterSure.notifyDataSetChanged()

        var sum = 0.0
        var totalGroup = 0
        checkInfoList.forEach {
            totalGroup += it.projectName.size
            sum += it.signMoney
        }
        tvSignGroupTotal.text = totalGroup.toString() + "组"
        tvCountSignMoney.text = sum.toString() + "元"

        tvCancel.setOnClickListener {
            dialogBottom.dismiss()
        }
        tvSUre.setOnClickListener {
            val param = SaveInfoSignParam(
                baseId = mBaseId,
                memberId = mMemberId,
                orderId = mOrderId,
                sInfo = sInfoBean,
                version = mVersion
            )
            showLoading(getString(R.string.loading))
            mViewModel.saveAppSignInfo(param)
        }
        ivCloseSingGroup.setOnClickListener {
            dialogBottom.dismiss()
        }
        dialogBottom.setContentView(dialogView)
        dialogBottom.show()
    }

    @SuppressLint("NotifyDataSetChanged")
    private fun searchRingPigeon() {
        val query = mDatabind.includeSearch.editQuery.text.toString().trim()
        val result = pigeonRawList.filter {
            it.ringId.contains(query, ignoreCase = true)
        }
        mAdapter.setList(result)
        mAdapter.notifyDataSetChanged()
    }

    private fun submitOrderSign() {
        var sumMoney: Int
        val checkInfoList: ArrayList<CheckInfoListBean> = arrayListOf()
        mAdapter.data.forEach { itR ->
            if (itR.isChecked && itR.isDisAble && itR.signStatus.isNotEmpty()) {
                val projectNameList: ArrayList<String> = arrayListOf()
                sumMoney = 0
                itR.signStatus.forEach {
                    if (it.isCheck && !it.isDisAble) {
                        sInfoBean.add(SInfoList(proId = it.projectId, ringId = itR.ringId))
                        projectNameList.add(it.projectName)
                    }
                    if (it.isCheck && !it.isDisAble) {
                        try {
                            val num: Int = it.money.toInt() // 将字符串转换为整数
                            sumMoney += num // 累加每个整数到总和
                        } catch (e: NumberFormatException) {
                            // 处理可能的格式异常，比如字符串不是一个有效的整数
                            e.printStackTrace()
                        }
                    }
                }

                checkInfoList.add(
                    CheckInfoListBean(
                        ringId = itR.ringId,
                        projectName = projectNameList,
                        signMoney = sumMoney.toDouble()
                    )
                )
            }
        }
        if (sInfoBean.isEmpty()) {
            RxToast.warning("暂无报名赛鸽")
            return
        }
        showBottomSureInfoDialog(checkInfoList, sInfoBean)
    }
}